package com.jt.auth.service;

import com.jt.auth.feign.RemoteUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 登录时用户信息的获取和封装会在此对象进行实现,
 * 在页面上点击登录按钮时,会调用这个对象的loadUserByUsername方法,
 * 页面上输入的用户名会传给这个方法的参数
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private RemoteUserService remoteUserService;
    //UserDetails用户封装用户信息(认证和权限信息)
    @Override
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {
        //1.基于用户名查询用户信息(用户名,用户状态,密码,....)
        com.jt.auth.pojo.User user=
                remoteUserService.selectUserByUsername(username);
        if(user==null)
            throw new UsernameNotFoundException("user is not exits");
        //2.查询用户权限信息(后面会访问数据库)
        List<String> permissions=
        remoteUserService.selectUserPermissions(user.getId());
        System.out.println("permissions="+permissions);
        List<GrantedAuthority> authorities =
        AuthorityUtils.createAuthorityList(//这里的权限信息先这么写,后面讲
                permissions.toArray(new String[]{}));
        //3.对用户信息进行封装
        return new User(username,user.getPassword(),authorities);
    }
}
